<template>
  <div class="price-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>房价管理</span>
          <el-button type="primary" @click="handleAddPriceStrategy" class="add-button">
            <el-icon-plus/>
            添加价格策略
          </el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="价格策略管理">
          <div class="search-container">
            <el-input
                v-model="strategySearchQuery"
                placeholder="请输入策略名称、房间类型"
                prefix-icon="Search"
                class="search-input"
            />
            <el-button type="primary" @click="handleStrategySearch">搜索</el-button>
          </div>

          <div class="table-container">
            <el-table v-loading="strategyLoading" :data="strategyList" style="width: 100%" max-width="100%">
              <el-table-column prop="id" label="策略ID" width="80"/>
              <el-table-column prop="name" label="策略名称" width="150"/>
              <el-table-column prop="roomType" label="房间类型" width="120"/>
              <el-table-column prop="basePrice" label="基础价格(元/月)" width="150"/>
              <el-table-column prop="startDate" label="生效起始日期" width="150"/>
              <el-table-column prop="endDate" label="生效结束日期" width="150"/>
              <el-table-column prop="remark" label="说明"/>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag
                      :type="scope.row.status === '生效中' ? 'success' : 'warning'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220" fixed="right">
                <template #default="scope">
                  <el-button size="small" @click="handleViewStrategyDetail(scope.row)">详情</el-button>
                  <el-button size="small" type="primary" @click="handleEditPriceStrategy(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDeletePriceStrategy(scope.row.id)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-container">
            <el-pagination
                v-model:current-page="strategyCurrentPage"
                v-model:page-size="strategyPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="strategyTotal"
                @size-change="handleStrategySizeChange"
                @current-change="handleStrategyCurrentChange"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="费用构成分析">
          <div class="chart-container">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>费用构成占比</span>
                </div>
              </template>
              <div ref="chartRef" class="chart"></div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑价格策略对话框 -->
    <el-dialog v-model="strategyDialogVisible" :title="strategyDialogTitle" draggable width="760px">
      <el-form :model="strategyFormData" ref="strategyFormRef" :rules="strategyRules" label-width="150px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="strategyFormData.name" placeholder="请输入策略名称"/>
        </el-form-item>
        <el-form-item label="房间类型" prop="roomType">
          <el-select v-model="strategyFormData.roomType" placeholder="请选择房间类型">
            <el-option label="一室一厅" value="一室一厅"/>
            <el-option label="两室一厅" value="两室一厅"/>
            <el-option label="三室一厅" value="三室一厅"/>
            <el-option label="三室两厅" value="三室两厅"/>
          </el-select>
        </el-form-item>
        <el-form-item label="基础价格(元/月)" prop="basePrice">
          <el-input v-model="strategyFormData.basePrice" type="number" placeholder="请输入基础价格"/>
        </el-form-item>
        <el-form-item label="旺季浮动比例(%)" prop="peakSeasonRate">
          <el-input v-model="strategyFormData.peakSeasonRate" type="number" placeholder="请输入旺季浮动比例"/>
        </el-form-item>
        <el-form-item label="生效起始日期" prop="startDate">
          <el-date-picker v-model="strategyFormData.startDate" type="date" placeholder="选择日期"/>
        </el-form-item>
        <el-form-item label="生效结束日期" prop="endDate">
          <el-date-picker v-model="strategyFormData.endDate" type="date" placeholder="选择日期"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="strategyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStrategySubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import * as echarts from 'echarts'
import priceService from '../../services/priceService.ts'
// 监听函数需要导入
import {watchEffect} from 'vue'
// 标签页相关
const activeTab = ref('0')

// 价格策略相关
const strategySearchQuery = ref('')
const strategyList = ref<any[]>([])
const strategyLoading = ref(false)
const strategyCurrentPage = ref(1)
const strategyPageSize = ref(10)
const strategyTotal = ref(0)
const strategyDialogVisible = ref(false)
const strategyDialogTitle = ref('添加价格策略')
const strategyFormData = reactive({
  id: '',
  name: '',
  roomType: '',
  basePrice: '',
  peakSeasonRate: 0,
  startDate: '',
  endDate: '',
  status: '未生效'
})
const strategyFormRef = ref<any>(null)
const strategyRules = {
  name: [{required: true, message: '请输入策略名称', trigger: 'blur'}],
  roomType: [{required: true, message: '请选择房间类型', trigger: 'change'}],
  basePrice: [
    {required: true, message: '请输入基础价格', trigger: 'blur'},
    {type: 'number', message: '基础价格必须为数字', trigger: 'blur'},
    {min: 1000, message: '基础价格不能小于1000元', trigger: 'blur'}
  ],
  peakSeasonRate: [
    {type: 'number', message: '浮动比例必须为数字', trigger: 'blur'},
    {min: 0, message: '浮动比例不能小于0%', trigger: 'blur'},
    {max: 100, message: '浮动比例不能大于100%', trigger: 'blur'}
  ],
  startDate: [{required: true, message: '请选择生效起始日期', trigger: 'change'}],
  endDate: [{required: true, message: '请选择生效结束日期', trigger: 'change'}]
}

// 图表相关
const chartRef = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 生命周期钩子
onMounted(() => {
  fetchStrategyList()
  // 监听标签页切换，在切换到图表标签时初始化图表
  activeTab.value = '0'
  watchEffect(() => {
    if (activeTab.value === '1') {
      nextTick(() => {
        initChart()
      })
    }
  })
})

// 初始化图表
const initChart = () => {
  if (chartRef.value && !chartInstance) {
    chartInstance = echarts.init(chartRef.value)
    // 从API获取图表数据
    priceService.getCostAnalysis().then((res: any) => {
      if (res.code === 200) {
        const option = {
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '5%',
            left: 'center'
          },
          series: [
            {
              name: '费用构成',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 20,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: res.data
            }
          ]
        }
        chartInstance.setOption(option)
      }
    }).catch((error: any) => {
      console.error('获取费用构成分析数据失败:', error)
      ElMessage.error('获取费用构成分析数据失败')
      // 使用默认数据
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '费用构成',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {value: 65, name: '租金'},
              {value: 15, name: '水电费'},
              {value: 10, name: '物业费'},
              {value: 10, name: '其他费用'}
            ]
          }
        ]
      }
      chartInstance.setOption(option)
    })
  }
}

// 获取价格策略列表
const fetchStrategyList = () => {
  strategyLoading.value = true
  priceService.getPriceList(strategyCurrentPage.value, strategyPageSize.value, strategySearchQuery.value).then((res: any) => {
    if (res.code === 200) {
      strategyList.value = res.data
      strategyTotal.value = res.total
      strategyLoading.value = false
    }
  }).catch((error: any) => {
    console.error('获取价格策略列表失败:', error)
    ElMessage.error('获取价格策略列表失败')
    strategyLoading.value = false
  })
}

// 价格策略搜索事件
const handleStrategySearch = () => {
  strategyCurrentPage.value = 1
  fetchStrategyList()
}

// 价格策略分页事件
const handleStrategySizeChange = (size: number) => {
  strategyPageSize.value = size
  fetchStrategyList()
}

const handleStrategyCurrentChange = (current: number) => {
  strategyCurrentPage.value = current
  fetchStrategyList()
}

// 添加价格策略
const handleAddPriceStrategy = () => {
  strategyDialogTitle.value = '添加价格策略'
  // 重置表单
  strategyFormData.id = ''
  strategyFormData.name = ''
  strategyFormData.roomType = ''
  strategyFormData.basePrice = ''
  strategyFormData.peakSeasonRate = 0
  strategyFormData.startDate = ''
  strategyFormData.endDate = ''
  if (strategyFormRef.value) {
    strategyFormRef.value.resetFields()
  }
  strategyDialogVisible.value = true
}

// 编辑价格策略
const handleEditPriceStrategy = (row: any) => {
  strategyDialogTitle.value = '编辑价格策略'
  // 填充表单数据
  Object.assign(strategyFormData, row)
  strategyDialogVisible.value = true
}

// 查看价格策略详情
const handleViewStrategyDetail = (row: any) => {
  ElMessage({
    message: `查看策略${row.name}的详情`,
    type: 'info'
  })
}

// 删除价格策略
const handleDeletePriceStrategy = (id: number) => {
  priceService.deletePrice(id).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: `删除价格策略ID: ${id} 成功`,
        type: 'success'
      })
      // 重新获取列表
      fetchStrategyList()
    }
  }).catch((error: any) => {
    console.error('删除价格策略失败:', error)
    ElMessage.error('删除价格策略失败')
  })
}

// 提交价格策略表单
const handleStrategySubmit = () => {
  strategyFormRef.value.validate((valid: boolean) => {
    if (valid) {
      strategyLoading.value = true
      if (strategyFormData.id) {
        priceService.updatePrice(Number(strategyFormData.id), strategyFormData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '编辑成功',
              type: 'success'
            })
            strategyDialogVisible.value = false
            fetchStrategyList()
          }
        }).catch((error: any) => {
          console.error('编辑价格策略失败:', error)
          ElMessage.error('编辑价格策略失败')
          strategyLoading.value = false
        })
      } else {
        priceService.createPrice(strategyFormData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '添加成功',
              type: 'success'
            })
            strategyDialogVisible.value = false
            fetchStrategyList()
          }
        }).catch((error: any) => {
          console.error('添加价格策略失败:', error)
          ElMessage.error('添加价格策略失败')
          strategyLoading.value = false
        })
      }
    }
  })
}


</script>

<style scoped>
.price-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-button {
  margin-top: 5px;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  width: 100%;
  overflow-x: auto;
  margin-bottom: 16px;
}

.chart-container {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.chart-card {
  width: 100%;
  max-width: 600px;
}

.chart {
  width: 100%;
  height: 400px;
}
</style>